package com.hc.baselibray.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.lang.ref.WeakReference;

public class DialogViewHelper {
    private View mContentView =null;
    //防止内存泄漏
    private SparseArray<WeakReference<View>> mViews=new SparseArray<>();

    private <T extends  View> T getView(int viewId){
      WeakReference<View> viewWeakReference=mViews.get(viewId);
        View view=null;
        if(viewWeakReference!=null){
                view=viewWeakReference.get();
        }
        if(view==null){
            view=mContentView.findViewById(viewId);
            if(view!=null){
                mViews.put(viewId,new WeakReference<>(view));
            }
        }
        return (T) view;
    };

    public View getmContentView() {
        return mContentView;
    }

    public DialogViewHelper(Context mContext, int mViewLayoutResId) {
        //为什么这里要调用this（）
          // this();
            mContentView= LayoutInflater.from(mContext).inflate(mViewLayoutResId,null);
    }

    public DialogViewHelper() {

    }

    public void setContentView(View mView) {
        mContentView=mView;
    }

    public void setText(int viewId, CharSequence text) {
        TextView tv=getView(viewId);
        if(tv!=null){
            tv.setText(text);
        }
    }

    public void setOnClickListener(int viewId, View.OnClickListener listener) {
        View view=getView(viewId);
        if(view!=null){
            view.setOnClickListener(listener);
        }
    }
}
